package leetcode.code977.SquaresofaSortedArray;

public class Solution2 implements ISquaresofaSortedArray {

	@Override
	public int[] sortedSquares(int[] nums) {
		int len = nums.length;
		if (len == 1) {
			return new int[] { nums[0] * nums[0] };
		}
		int[] result = new int[len];
		// -4,-1,0,3,10
		int pointl = 0;
		int pointr = len - 1;
		int ll = Integer.MAX_VALUE;
		int rr = Integer.MIN_VALUE;
		int pointResult = len - 1;
		rr = nums[pointr] * nums[pointr];
		ll = nums[pointl] * nums[pointl];
//		[-5,-3,-2,-1]
		while (pointl <= pointr) {
			if (rr > ll) {
				result[pointResult] = rr;
				pointResult--;
				if (pointr == 0)
					break;
				pointr--;
				rr = nums[pointr] * nums[pointr];
			} else {
				result[pointResult] = ll;
				pointResult--;
				if (pointl == len - 1)
					break;
				pointl++;
				ll = nums[pointl] * nums[pointl];// 这里越界了
			}
		}
		return result;
	}

	public static void main(String[] args) {
		Solution2 so = new Solution2();
		so.myPrint1();
		so.myPrint2();
		so.myPrint3();
		so.myPrint4();
	}

//	输入：nums = [-4,-1,0,3,10]
//  输出：[0,1,9,16,100]
//	解释：平方后，数组变为 [16,1,0,9,100]
//	排序后，数组变为 [0,1,9,16,100]

	public void myPrint1() {
		int[] nums = { -4, -1, 0, 3, 10 };
		this.debug(nums);
	}

//	输入：nums = [-7,-3,2,3,11]
//	输出：[4,9,9,49,121]

	public void myPrint2() {
		int[] nums = { -7, -3, 2, 3, 11 };
		this.debug(nums);
	}

//	输入：nums = [-1]
//	输出：[1]

	public void myPrint3() {
		int[] nums = { -1 };
		this.debug(nums);
	}

//	[-5,-3,-2,-1]

	public void myPrint4() {
		int[] nums = { -5, -3, -2, -1 };
		this.debug(nums);
	}

	private void debug(int[] nums) {
		ISquaresofaSortedArray solution = new Solution2();
		int[] result = solution.sortedSquares(nums);
		for (int i : result) {
			System.out.print(i + ",");
		}
		System.out.println(" ");
	}

}
